﻿#include "itemadd.h"
#include "ui_itemadd.h"

ItemAdd::ItemAdd(QWidget *parent, const QString &table, const QString &entry) :
    QDialog(parent),
    _table(table),
    _entry(entry),
    ui(new Ui::ItemAdd)
{
    ui->setupUi(this);
}

ItemAdd::~ItemAdd()
{
    delete ui;
}

bool ItemAdd::addItem(const QString &category,
                      const QString &label, const QString &detail,
                      const QString &addition)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (category,label,detail,addition,entry) values (?,?,?,?,?)").arg(_table));
    query.addBindValue(category);
    query.addBindValue(label);
    query.addBindValue(detail);
    query.addBindValue(addition);
    query.addBindValue(_entry);
    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void ItemAdd::setCategory(const QString &category)
{
    ui->category->setText(category);
}

void ItemAdd::setCategoryPlaceholderText(const QString &category)
{
    ui->category->setPlaceholderText(category);
}

void ItemAdd::setLabelPlaceholderText(const QString &label)
{
    ui->label->setPlaceholderText(label);
}

void ItemAdd::setDetailPlaceholderText(const QString &detail)
{
    ui->detail->setPlaceholderText(detail);
}

void ItemAdd::setAdditionPlaceholderText(const QString &addition)
{
    ui->addition->setPlaceholderText(addition);
}

void ItemAdd::setAdditionDisable()
{
    ui->addition->setVisible(false);
}

void ItemAdd::on_btn_submit_clicked()
{
    QString category=ui->category->text().trimmed();
    if(category.isEmpty())
        return;

    QString label=ui->label->text().trimmed();
    if(label.isEmpty())
        return;

    QString detail=ui->detail->text().trimmed();
    if(detail.isEmpty())
        return;

    QString addition=ui->addition->text().trimmed();

    if(!addItem(category,label,detail,addition))
        QMessageBox::warning(this,QStringLiteral("异常情况"),QStringLiteral("无法提交数据！"));
    else
        this->accept();
}
